<?php
require_once dirname(__FILE__) . '/includes/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";
  
header('Content-Type: text/plain');

$class = MiscUtils::getParam('name', NULL);
$objectsToAddOrUpdate = json_decode(MiscUtils::getParam('obj', NULL));
$objectsToRemove = json_decode(MiscUtils::getParam('r', NULL));

try {
  $hostname = HOST_NAME;
  $username = USER_NAME;
  $password = PASSWORD;
  $dbname = DATABASE_NAME;
  $myPdo = new PDO ('mysql:host=' . $hostname, $username, $password);
  $myPdo->exec('USE ' . $dbname);
  $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  echo $e->getMessage ();
}

$orm = classToOrm($class);
if ($orm) {
  try {
    $myPdo->beginTransaction ();
    foreach ($objectsToAddOrUpdate as &$object) {
      if (isset($object->id)) {
        //MiscUtils::dump(MiscUtils::obj2Upd($orm->dto, $object));
        $myPdo->exec(MiscUtils::obj2Upd($orm->dto, $object));
      } else {
        //MiscUtils::dump(MiscUtils::obj2Ins($orm->dto, $object));
        $myPdo->exec(MiscUtils::obj2Ins($orm->dto, $object));
      }
    }
    foreach ($objectsToRemove as &$object) {
      //MiscUtils::dump(MiscUtils::obj2Del($orm->dto, $object));
      $myPdo->exec(MiscUtils::obj2Del($orm->dto, $object));
    }
    $myPdo->commit ();
    echo json_encode(array());
  } catch (PDOException $e) {
    $myPdo->rollBack();
    echo $e->getMessage();
  }
}
?>